#include <stdio.h>
#include <stdbool.h>

#include "los_task.h"
#include "ohos_init.h"
#include "cmsis_os.h"
#include "config_network.h"
#include "iot_pwm.h"

#include "device_mgr.h"
#include "iot.h"
#include "tcp.h"

// #define ROUTE_SSID "CU_2b5f" // WiFi账号
// #define ROUTE_PASSWORD "3a8085ca" // WiFi密码
// #define ROUTE_SSID "ISS202411" // WiFi账号
// #define ROUTE_PASSWORD "Aa123456" // WiFi密码
// #define ROUTE_SSID "CMCC-8208" // WiFi账号
// #define ROUTE_PASSWORD "88888888" // WiFi密码
// #define ROUTE_SSID "vivo" // WiFi账号
// #define ROUTE_PASSWORD "30824453" // WiFi密码
#define ROUTE_SSID "OH_WIFI" // WiFi账号
#define ROUTE_PASSWORD "12345678" // WiFi密码
// #define ROUTE_SSID "W01X-1EF9" // WiFi账号
// #define ROUTE_PASSWORD "1234567890" // WiFi密码

#define MSG_QUEUE_LENGTH 16
#define BUFFER_LEN 50

#define BEEP_PORT EPWMDEV_PWM5_M0

bool human_state = false;
bool light_state = false;
bool auto_state = true;

static unsigned int m_msg_queue;

/***************************************************************
 * 函数名称: iot_thread
 * 说 明: iot线程
 * 参 数: 无
 * 返 回 值: 无
 ***************************************************************/
void iot_thread(void *args)
{
    uint8_t mac_address[6] = {0x00, 0xdc, 0xb6, 0x90, 0x01, 0x00};

    FlashInit();
    VendorSet(VENDOR_ID_WIFI_MODE, "STA", 3); // 配置为Wifi STA模式
    VendorSet(VENDOR_ID_MAC, mac_address, 6); // 多人同时做该实验，请修改各自不同的WiFi MAC地址
    VendorSet(VENDOR_ID_WIFI_ROUTE_SSID, ROUTE_SSID, sizeof(ROUTE_SSID));
    VendorSet(VENDOR_ID_WIFI_ROUTE_PASSWD, ROUTE_PASSWORD, sizeof(ROUTE_PASSWORD));

reconnect:
    SetWifiModeOff();
    SetWifiModeOn();

    // mqtt_init();

    // while (1)
    // {
    //     if (!wait_message())
    //     {
    //         goto reconnect;
    //     }
    //     LOS_Msleep(1);
    // }
}

/***************************************************************
 * 函数名称: device_ctl_thread
 * 说 明: 设备控制任务
 * 参 数: 无
 * 返 回 值: 无
 ***************************************************************/
void device_ctl_thread(void *arg)
{
    double *data_ptr = NULL;

    // 新增：灯光阈值
    e_iot_data iot_data = {0};

    lcd_dev_init();
    lcd_load_ui();
    light_dev_init();
    // body_induction_dev_init();
    door_init();

    iss_mq2_dev_s mq2_init;
    // mq2_dev_init(&mq2_init);
    gpio_dev_init();

    IoTPwmInit(BEEP_PORT);


    while (1)
    {
        LOS_QueueRead(m_msg_queue, (void *)&data_ptr, BUFFER_LEN, LOS_WAIT_FOREVER);
        // for (int iLoop = 0; iLoop < BUFFER_LEN; ++iLoop) {
        //     printf("data_ptr[%d] = %.02f\n", iLoop, data_ptr[iLoop]);
        // }

        if (!auto_state)
        {
            // light_set_state(light_state);
        }
        else
        {
            // bool bHumanDetected = body_induction_get_state();
            // if (bHumanDetected == true)
            // {
            //     light_state = true;
            //     human_state = true;
            //     // light_set_state(true);
            // }
            // else
            // {
            //     light_state = false;
            //     human_state = false;
            //     // light_set_state(light_state);
            // }
        }

        // lcd_set_light_state(light_state);
        // lcd_set_auto_state(auto_state);
        // lcd_set_human_state(human_state);
        // float gas = get_mq2_ppm();
        // printf("Gas: %.2f ppm\n", gas);


        // if (mqtt_is_connected())
        // {
        //     // 发送iot数据
        //     iot_data.light_state = light_state;
        //     iot_data.auto_state = auto_state;
        //     iot_data.human_state = human_state;
        //     send_msg_to_mqtt(&iot_data);
        // }


        LOS_Msleep(3000);
    }
}

/***************************************************************
 * 函数名称: device_read_thraed
 * 说 明: 设备读取线程
 * 参 数: 无
 * 返 回 值: 无
 ***************************************************************/
void device_read_thraed(void *arg)
{
    printf("device_read_thraed enter...\n");

    float read_data[4] = {0};

    i2c_dev_init();
    LOS_Msleep(1000);

    while (1)
    {
        get_light_value(&read_data[0]);
        // printf("Light: %.2f lux\n", read_data[0]);

        get_tmp_hum_value(&read_data[1], &read_data[2]);
        // printf("Temperature: %.2f °C, Humidity: %.2f %%\n", read_data[1], read_data[2]);
        // sht30_read_data(&read_data[1]);

        char key = 0;
        get_key_pressed(&key);
        if (key == 'A')
        {
            light_state = !light_state;
            light_control(light_state);
        }
        // printf("Key (%x): %c\n", key, key);

        // read_data[3] = get_mq2_ppm();

        LOS_QueueWrite(m_msg_queue, (void *)&read_data, sizeof(read_data), LOS_WAIT_FOREVER);
        memset(g_message_send, 0, sizeof(g_message_send));
        sprintf(g_message_send, "TMP:%.2f;HUM:%.2f;Light:%d;DOOR:ON", read_data[1], read_data[2], (int)read_data[0]);
        printf("Upload message:%s\n", g_message_send);
        LOS_Msleep(2000);
    }
}

void wifi_process(void *args)
{
    unsigned int threadID_client, threadID_server;
    unsigned int ret = LOS_OK;

    set_wifi_config_route_ssid(printf,   ROUTE_SSID);     	// 路由的WiFi名称
    set_wifi_config_route_passwd(printf, ROUTE_PASSWORD);   // 路由器WiFi密码

    SetWifiModeOff();
    SetApModeOff();
    SetWifiModeOn();
   
    WifiLinkedInfo info;

    while(get_wifi_info(&info) != 0)
    {
        printf(".");
    }

    CreateThread(&threadID_client,  wifi_client, NULL, "client@ process");
    CreateThread(&threadID_server,  wifi_server, NULL, "server@ process");
}

/***************************************************************
 * 函数名称: smart_house_entry
 * 说 明: 开机自启动调用函数
 * 参 数: 无
 * 返 回 值: 无
 ***************************************************************/
void smart_house_entry()
{
    unsigned int thread_id_1 = 0;
    unsigned int thread_id_2 = 0;
    unsigned int thread_id_3 = 0;
    unsigned int thread_id_4 = 0;
    TSK_INIT_PARAM_S task_1 = {0};
    TSK_INIT_PARAM_S task_2 = {0};
    TSK_INIT_PARAM_S task_3 = {0};
    TSK_INIT_PARAM_S task_4 = {0};
    unsigned int ret = LOS_OK;

    ret = LOS_QueueCreate("queue", MSG_QUEUE_LENGTH, &m_msg_queue, 0, BUFFER_LEN);
    if (ret != LOS_OK)
    {
        printf("Falied to create Message Queue ret:0x%x\n", ret);
        return;
    }

    task_1.pfnTaskEntry = (TSK_ENTRY_FUNC)device_ctl_thread;
    task_1.uwStackSize = 2048;
    task_1.pcName = "device control thread";
    task_1.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_1, &task_1);
    if (ret != LOS_OK)
    {
        printf("Falied to create task ret:0x%x\n", ret);
        return;
    }

    task_2.pfnTaskEntry = (TSK_ENTRY_FUNC)device_read_thraed;
    task_2.uwStackSize = 2048;
    task_2.pcName = "device read thraed";
    task_2.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_2, &task_2);
    if (ret != LOS_OK)
    {
        printf("Falied to create task ret:0x%x\n", ret);
        return;
    }

    // task_3.pfnTaskEntry = (TSK_ENTRY_FUNC)iot_thread;
    // task_3.uwStackSize = 20480;
    // task_3.pcName = "iot thread";
    // task_3.usTaskPrio = 24;
    // ret = LOS_TaskCreate(&thread_id_3, &task_3);
    // if (ret != LOS_OK)
    // {
    //     printf("Falied to create task ret:0x%x\n", ret);
    //     return;
    // }
        
    task_4.pfnTaskEntry = (TSK_ENTRY_FUNC)wifi_process;
    task_4.uwStackSize = 10240;
    task_4.pcName = "wifi_process";
    task_4.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_4, &task_4);
    if (ret != LOS_OK)
    {
        printf("Falied to create wifi_process ret:0x%x\n", ret);
        return;
    }
}

APP_FEATURE_INIT(smart_house_entry);